package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.base.response.JsonResult;
import cn.tedu._05weibo.base.response.StatusCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
@Api(tags = "用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @ApiOperation("注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if ((userVO != null)){
            return new JsonResult(StatusCode.USERNAME_EXIST);
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);


        return JsonResult.ok();
    }
    @ApiOperation("登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserRegDTO userRegDTO, HttpSession session){
        String username = userRegDTO.getUsername();
        UserVO userVO = userMapper.selectByUsername(username);
        if ((userVO != null) && userVO.getPassword().equals(userRegDTO.getPassword())){
            session.setAttribute("user",userVO);
            return JsonResult.ok(userVO);
        }
        if (userVO == null){
            return new JsonResult(StatusCode.PASSWORD_ERROR);
        }
        return new JsonResult(StatusCode.USERNAME_ERROR);
    }
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        return (UserVO) session.getAttribute("user");
    }

    @ApiOperation("退出功能")
    @GetMapping("logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }



}
